export const exportNotesToCSV = (notes: Note[]): string => {
  const headers = ['id', 'title', 'body', 'updated', 'tags'];
  const csv = [
    headers.join(','),
    ...notes.map(note => {
      const tags = note.tags ? note.tags.join(';') : '';
      return `${note.id},"${note.title.replace(/"/g, '""')}","${note.body.replace(/"/g, '""')}","${note.updated}","${tags}"`;
    })
  ].join('\n');
  return csv;
};

export const importNotesFromCSV = (csv: string): Note[] => {
  const lines = csv.split('\n');
  const headers = lines[0].split(',');
  
  return lines.slice(1)
    .map(line => {
      // 使用正则表达式正确处理带引号的CSV
      const values = line.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
      if (!values) return null;
      
      const note: any = {};
      headers.forEach((header, index) => {
        if (header === 'tags') {
          note[header] = values[index].replace(/"/g, '').split(';').filter(Boolean);
        } else {
          note[header] = values[index].replace(/"/g, '');
        }
      });
      
      // 验证导入的数据
      if (!note.title || !note.body) return null;
      
      return {
        ...note,
        id: parseInt(note.id) || Math.floor(Math.random() * 1000000),
        updated: note.updated || new Date().toISOString()
      };
    })
    .filter(Boolean) as Note[];
};
